package cn.yitun.chat.yitunserverimcore.general.main.biz.chat.manager;

import cn.yitun.chat.yituncommonutil.YitunMapUtil;
import cn.yitun.chat.yituncommonutil.YitunStringUtil;
import cn.yitun.chat.yitunservercommonlib.converter.dto2vo.user.UserLastChatDto2VoConverter;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.base.chat.ChatItem;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.userchat.LastChatDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.userchat.UserChatContentDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.userchat.UserChatItemDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.system.user.UserVo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.userchat.LastChatVo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.userchat.UserChatContentVo;
import cn.yitun.chat.yitunservercommonlib.enums.userChat.UserChatTypeEnums;
import cn.yitun.chat.yitunservercommonlib.util.codec.IdGen;
import cn.yitun.chat.yitunserverimbase.dao.userchat.LastChatDao;
import cn.yitun.chat.yitunserverimbase.dao.userchat.UserChatContentDao;
import cn.yitun.chat.yitunserverimbase.dao.userchat.UserChatItemDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户聊天
 * @author yitun
 * @date 2017-11-26 13:01:51
 */
@Service
public class UserChatManager {

	@Resource
	private UserChatContentDao userChatDAO;
	@Resource
	private UserChatItemDao userChatItemDao;
	@Resource
	private LastChatDao userLastChatDAO;

	@Transactional
	public void addUserChatHistory(
			boolean isSend,
			UserVo sendUserData,
			UserVo receiveUserData,
			Long messageKey,
			List<ChatItem> chatItemList) {
		messageKey = null == messageKey  ? IdGen.getNumber() : messageKey;
		UserChatContentDto content = createUserChatContent(isSend, messageKey, sendUserData, receiveUserData);
		userChatDAO.save(content);
		List<UserChatItemDto> list = new ArrayList<>();
		for (ChatItem item : chatItemList) {
			if (YitunStringUtil.isEmpty(item.getValue()))
				continue;

			UserChatItemDto chatLog = new UserChatItemDto();
			chatLog.setMessageId(messageKey);
			chatLog.setUserChatContentId(content.getId());
			chatLog.setSendUserId(content.getSendUserId());
			chatLog.setReceiveUserId(content.getReceiveUserId());
			chatLog.setRank(item.getRank());
			chatLog.setSection(item.getSection());
			chatLog.setType(item.getType());
			chatLog.setValue(item.getValue());
			chatLog.setFilterValue(item.getFilterValue());
			chatLog.setCreateBy(content.getSendUserId());
			chatLog.setUpdateBy(content.getSendUserId());
			list.add(chatLog);
		}
		userChatItemDao.saveList(list);
		Long sendId = sendUserData.getId();
		Long receiveId = receiveUserData.getId();
		LastChatDto userLastChat1 = createUserLastChat(messageKey, content.getId(), sendId, receiveId, UserChatTypeEnums.TYPE_USER.getType());
		userLastChat1.setCreateBy(content.getSendUserId());
		userLastChat1.setUpdateBy(content.getSendUserId());
		saveOrUpdateLast(userLastChat1);
		//判断是否自发自收
		if (!sendId.equals(receiveId)) {
			LastChatDto userLastChat2 = createUserLastChat(messageKey, content.getId(), receiveId, sendId, UserChatTypeEnums.TYPE_USER.getType());
			userLastChat2.setCreateBy(content.getSendUserId());
			userLastChat2.setUpdateBy(content.getSendUserId());
			saveOrUpdateLast(userLastChat2);
		}
	}

	/**
	 * 创建用户聊天记录
	 * @param isSend
	 * @param messageKey
	 * @param sendUserData
	 * @param receiveUserData
	 * @return
	 */
	private UserChatContentDto createUserChatContent(boolean isSend, Long messageKey, UserVo sendUserData, UserVo receiveUserData) {
		UserChatContentDto chatLog = new UserChatContentDto();
		chatLog.setMessageId(messageKey);
		chatLog.setIsSend(isSend ? 1 : 0);

		chatLog.setReceiveUserHead(receiveUserData.getHead());
		chatLog.setReceiveUserAvatar(receiveUserData.getAvatar());
		chatLog.setReceiveUserId(receiveUserData.getId());
		chatLog.setReceiveUserName(receiveUserData.getName());
		chatLog.setReceiveUserNickname(receiveUserData.getNickname());
		chatLog.setReceiveUserRemarkName("");
		// chatLog.setReceiveUserRole(receiveUserRole);

		chatLog.setSendUserHead(sendUserData.getHead());
		chatLog.setSendUserAvatar(sendUserData.getAvatar());
		chatLog.setSendUserId(sendUserData.getId());
		chatLog.setSendUserName(sendUserData.getName());
		chatLog.setSendUserNickname(sendUserData.getNickname());
		chatLog.setSendUserRemarkName("");

		chatLog.setUpdateBy(sendUserData.getId());
		chatLog.setCreateBy(sendUserData.getId());

		return chatLog;
	}

	/**
	 * 创建用户最后聊天记录
	 * @param messageKey
	 * @param contentId
	 * @param userId
	 * @param chatId
	 * @param type
	 * @return
	 */
	private LastChatDto createUserLastChat(Long messageKey, Long contentId, Long userId, Long chatId, String type) {

		long timestamp = System.currentTimeMillis();

		LastChatDto bean = new LastChatDto();
		bean.setChatId(chatId);
		bean.setContentId(contentId);
		bean.setMessageId(messageKey);
		bean.setType(type);
		bean.setUserId(userId);
		return bean;
	}

	/**
	 * 保存
	 * @param userLastChat
	 */
	private void saveOrUpdateLast(LastChatDto userLastChat) {
		saveOrUpdate(userLastChat);
	}

	/**
	 * 保存
	 * @param userLastChat
	 */
	public void saveOrUpdate(LastChatDto userLastChat) {
		LastChatVo bean = userLastChatDAO.getLastChat(userLastChat.getUserId(), userLastChat.getChatId(), userLastChat.getType());
		if (null != bean) {
			// bean.setMessageKey(userLastChat.getMessageKey());
			// 更新最后聊天
            bean.setMessageId(userLastChat.getMessageId());
            bean.setContentId(userLastChat.getContentId());
            bean.setUpdateBy(userLastChat.getUserId());
			userLastChatDAO.update(UserLastChatDto2VoConverter.INSTANCE.vo2dto(bean));
		} else {
		    // 新增
            userLastChat.setUpdateBy(userLastChat.getUserId());
			userLastChat.setCreateBy(userLastChat.getUserId());
			userLastChatDAO.save(userLastChat);
		}
	}

	/**
	 * 获取未读 计数
	 * @param query
	 * @return
	 */
    public int queryUserChatUnreadCount(UserChatContentDto query) {
    	return userChatDAO.count(YitunMapUtil.java2Map(query, false));
    }

	/**
	 * 获取未读 列表
	 * @param query
	 * @return
	 */
	public List<UserChatContentVo> queryUserChatUnreadList(UserChatContentDto query) {
    	return userChatDAO.listVO(YitunMapUtil.java2Map(query, false));
	}
}
